package cn.nawang.ebeim.test.service;

import cn.nawang.ebeim.test.constants.Config;
import cn.nawang.ebeim.test.db.DBHelper;
import cn.nawang.ebeim.test.domain.FileInfo;
import cn.nawang.ebeim.test.domain.Root;
import cn.nawang.ebeim.test.queue.Queues;
import cn.nawang.ebeim.test.task.UploadTask;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * Created by GanJc on 2015-12-08 10:51
 */
public class UploadService {

    private static final Logger LOG = LoggerFactory.getLogger(UploadService.class);

    /**
     * 上传的根目录
     */
    private String rootDir ;

    /**
     * 相对路径
     */
    private static String absDir  ;

    /**
     * 文件夹数量
     */
    private  int dirCount = 0;

    /**
     * 文件数量
     */
    private  int fileCount = 0;

    private DBHelper dbHelper ;

    private List<FileInfo> files = new ArrayList<>();

    public UploadService(String rootDir) {
        this.rootDir = rootDir;
        dbHelper = new DBHelper();
    }

    public void upload(){
        LOG.info(rootDir);
        File file = new File(rootDir);
        if(file.isDirectory()){
            absDir = file.getName();
            listFiles(file);
        }
        LOG.info("文件夹数量：" + dirCount);
        LOG.info("文件数量：" + fileCount);
        TestData.setTotalTransferFile(fileCount);
        try {
            dbHelper.saveRoot(new Root(rootDir,absDir,dirCount,fileCount));
//            dbHelper.saveFiles(files);
        } catch (SQLException e) {
            e.printStackTrace();
        }

    }

    public void listFiles(File file){
        if (file.isDirectory()) {
            File[] files = file.listFiles();
            for (File f : files) {
                listFiles(f);
            }
            dirCount++;
        } else {
            String aPath = file.getAbsolutePath();
            aPath = aPath.substring(rootDir.length(),aPath.length());
            String signature = UUID.randomUUID().toString();
            LOG.info(aPath);
            String container = Config.CONTAINER;
            FileInfo fileInfo = new FileInfo(container,signature,aPath, rootDir, absDir);
//            files.add(fileInfo);
            try {
                dbHelper.saveFile(fileInfo);
                cn.nawang.ebeim.test.transfer.FileInfo info = new cn.nawang.ebeim.test.transfer.FileInfo();
                info.setDataId(container);
                info.setSignature(signature);
                info.setPath(file.getAbsolutePath());
                info.setType(cn.nawang.ebeim.test.transfer.FileInfo.TYPE_FILE_UPLOAD);
                Queues.uploadTaskQueue.put(new UploadTask(info));
            } catch (SQLException e) {
                e.printStackTrace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            fileCount++;
        }
    }

}
